package androidServlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.tecnick.htmlutils.htmlentities.HTMLEntities;

import sessionMenegment.SessionMgr;

import controller.Controller;
import dataBase.Order;

@SuppressWarnings("serial")
public class ClientOrdersAndroid extends HttpServlet {

	private SimpleDateFormat formatter;

	public ClientOrdersAndroid() {
		formatter = new SimpleDateFormat("dd-MM-yy");
		formatter.setTimeZone(TimeZone.getTimeZone("Israel"));
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {

		String userName = req.getParameter("username");
		String bizName = null;
		List<Order> clientOrders = Controller.getInstance().getClientOrders(userName);


		System.out.println("client orders - android. size: "+clientOrders.size());


		PrintWriter out = resp.getWriter();
		boolean first = true;
		out.println("{\"orders\": [");

		if (clientOrders!=null)
		{
			for (Order order: clientOrders)
			{

				bizName = Controller.getInstance().userNameToBizName(order.getBusinessUserName());
				
				if (first)
					first = false;
				else
					out.println(",");


				out.println("  {");
				out.print("    \"orderNum\": ");
				out.print(order.getOrderNum());
				out.println(',');
				out.print("    \"key\": ");
				out.print(order.getKey().getId());
				out.println(',');
				out.print("    \"date\": ");
				out.print(formatter.format(order.getStartTime()));
				out.println(",");
				out.print("    \"from\": ");
				out.print("\""+bizName+"\"");
				out.println(',');
				out.print("    \"fromKey\": ");
				out.print("\""+Controller.getInstance().bizNameToKeyID(bizName)+"\"");
				out.println(',');
				out.print("    \"phone\": ");
				out.print("\""+order.getPhoneNumber().getNumber()+"\"");
				out.println(',');
				out.print("    \"status\": ");
				out.println("\""+Controller.getInstance().getCurrentStatusOfOrder(order)+"\"");
				out.println("  }");

			}
		}

		out.println("] }");
		out.flush();


	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {

	}

}
